package org.flower.web.servlet;

import org.flower.dao.CollectDao;
import org.flower.dao.CommodityDetailsDao;
import org.flower.dao.impl.CollectDaoImpl;
import org.flower.dao.impl.CommodityDetailsDaoImpl;
import org.flower.entity.CommodityDetails;
import org.flower.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/commodityDetails.shtml")
public class commodityDetailsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理字符编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取商品编号
        String idStr = request.getParameter("id");
        //创建底层对象
        CommodityDetailsDao cdao = new CommodityDetailsDaoImpl();
        //根据商品编号查询商品详情信息
        CommodityDetails com = cdao.getComdetailsById(Integer.parseInt(idStr));
        //处理商品信息中的商品名称个商品描述
        String comName = com.getComName();
        if(comName.indexOf("·")>=0){
            //如果 商品名称中有 点  就取出点后边的值作为商品名称
            com.setComName(comName.split("·")[1]);
        }
        String content = com.getContent();
        if(content.indexOf("split")>=0){
            com.setContent(content.split("split")[0]);
            com.setContent2(content.split("split")[1]);
        }
        //处理商品图片
        List<String> strImages =  new ArrayList<String>();
        for(String str : com.getComImage().split(",")){
            strImages.add(str);
        }
        com.setImages(strImages);
        //创建 商品收藏字符串 默认为空
        String collect = null;
        CollectDao ldao = new CollectDaoImpl();
        //获取登录的该用户
        User u = (User)request.getSession().getAttribute("user");
        if(u!=null){
            //查询该用户是否收藏了该商品
            boolean exist = ldao.getCollectExistByUidAndComId(u.getId(),Integer.parseInt(idStr));
            if(exist){
                //如果收藏过该商品 将收藏字符串赋值active
                collect = "active";
            }
        }
        //获取该商品的 同类商品
        List<CommodityDetails> similarCommodity = cdao.getCommodityDetailsByShowId(com.getId(), com.getComShowId());
        //最后 将该对象信息保存到request作用域中 转发页面OK
        request.setAttribute("collect",collect);
        request.setAttribute("similarCommodity",similarCommodity);
        request.setAttribute("commDetails",com);
        request.getRequestDispatcher("commodityDetails.jsp").forward(request,response);

    }
}
